package com.gobo.jinghuimall.ware.service.impl;

import com.gobo.common.constant.WareConstant;
import com.gobo.jinghuimall.ware.entity.PurchaseDetailEntity;
import com.gobo.jinghuimall.ware.service.PurchaseDetailService;
import com.gobo.jinghuimall.ware.service.WareSkuService;
import com.gobo.jinghuimall.ware.vo.MergeVo;
import com.gobo.jinghuimall.ware.vo.PurchaseDetailDoneVo;
import com.gobo.jinghuimall.ware.vo.PurchaseDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gobo.common.utils.PageUtils;
import com.gobo.common.utils.Query;

import com.gobo.jinghuimall.ware.dao.PurchaseDao;
import com.gobo.jinghuimall.ware.entity.PurchaseEntity;
import com.gobo.jinghuimall.ware.service.PurchaseService;
import org.springframework.util.StringUtils;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    WareSkuService wareSkuService;

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }
    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> purchaseEntityQueryWrapper = new QueryWrapper<>();
        purchaseEntityQueryWrapper.eq("status",WareConstant.PurchaseStatusEnum.CREATED.getCode())
                .or().eq("status",WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                purchaseEntityQueryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageCondition(Map<String, Object> params) {
        //TODO
        QueryWrapper<PurchaseEntity> purchaseEntityQueryWrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            purchaseEntityQueryWrapper.and(o->{
                o.eq("id",key).or()
                        .like("assignee_name",key);
            });
        }


        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                purchaseEntityQueryWrapper

        );

        return new PageUtils(page);

    }

    @Override
    public void saveMerge(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId==null || purchaseId==0L){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //采购单状态是0,1才可以合并
        PurchaseEntity byId = this.getById(purchaseId);
        if (byId.getStatus()==WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
        byId.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()){

            List<Long> items = mergeVo.getItems();
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> collect = items.stream().map(o -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(o);
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);
            //更新采购单状态
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(purchaseId);
            purchaseEntity.setUpdateTime(new Date());
            this.updateById(purchaseEntity);
        }
    }

    /**
     * 领取采购单
     * @param ids
     */
    @Override
    public void receivedPurchase(List<Long> ids) {
        if (ids==null || ids.size()<=0) {return;}
        List<PurchaseEntity> collect = ids.stream().map(obj -> {
            //1、确认当前采购单是新建或者已分配状态
            PurchaseEntity byId = this.getById(obj);
            return byId;
        }).filter(obj -> {
            if (obj.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode() ||
                    obj.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()) {
                return true;
            }
            return false;
        }).map(o -> {
            o.setUpdateTime(new Date());
            o.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            return o;
        }).collect(Collectors.toList());

        //2、改变采购单的状态
        this.updateBatchById(collect);
        //3、改变采购项的状态
        collect.forEach(o->{
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listDetailByPurchaseId(o.getId());
            List<PurchaseDetailEntity> collect1 = purchaseDetailEntities.stream().map(obj -> {
                obj.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return obj;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect1);
        });
    }
    /**
     *完成采购单
     */
    @Override
    public void purchaseDone(PurchaseDoneVo purchaseDoneVo){
        //2、改变采购项的状态
        Long purchaseId = purchaseDoneVo.getId();
        Boolean flag = true;
        List<PurchaseDetailDoneVo> items = purchaseDoneVo.getItems();
        List<PurchaseDetailEntity> addList = new ArrayList<>();
        for (PurchaseDetailDoneVo item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if (item.getStatus()==WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                purchaseDetailEntity.setStatus(item.getStatus());
                flag = false;
            }else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                ////3、将成功采购的进行入库 TODO
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuNum(),entity.getSkuId(),entity.getWareId());
            }
            purchaseDetailEntity.setId(item.getItemId());
            addList.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(addList);
        //1、改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }
}